package com.geetol.makename.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.geetol.makename.R;
import com.geetol.makename.base.BaseActivity;
import com.geetol.makename.http.beans.NameInfo;
import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;
import com.gtdev5.geetolsdk.mylibrary.util.Utils;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Info     ： Create by Zeoy
 * Introduce：百家姓详情  * 姓名起源
 * Date     ： 2019/5/23
 */

public class ExplainBaiJiaNameActivity extends BaseActivity {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rv)
    TextView rv;
    @BindView(R.id.tv_right_bt)
    TextView tvRightBt;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.webView)
    WebView webView;
    private String name = "zhou";
    private String url1;
//    https://xing.911cha.com/xing_%E9%94%85.html

    @Override
    protected int getLayoutId() {
        return R.layout.activity_explain_bajianame_layout;
    }

    private  String title = "";

    @Override
    public void initView() {
        if (getIntent() != null) {
            url1 = getIntent().getStringExtra("name");
            tvTitleName.setText(url1);
        }
        tvTitle.setText("姓氏起源");
        ivTitleBack.setVisibility(View.VISIBLE);
        ivTitleBack.setOnClickListener(v -> finish());
        url1 = "https://xing.911cha.com/xing_"+ url1 +".html";
        if (Utils.isNetworkAvailable(getContext())) {
            getDataByJsoup1();
            showLoading();
        }else{
            ToastUtils.showShortToast("请检查网络连接状态");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private void getDataByJsoup1() {
        new Thread(() -> {
            try {
                StringBuilder stringBuilder = new StringBuilder();
                Connection connect = Jsoup.connect(url1);
                connect.timeout(3000);
                Document doc = connect.get();
                Elements titleLinks = doc.select("div.cont");
                for(Element edd :titleLinks ){
                    String s = edd.select("p").text();
                    stringBuilder.append("    ").append(s).append("\n\n");
                }
                handler.postDelayed(() -> {
                    if (stringBuilder.length() > 0) {
                        title = stringBuilder.toString();
                        Message message = new Message();
                        message.obj = title;
                        message.what = 1;
                        handler.sendMessage(message);
                    } else {
                        getWebViewData();
                    }
                }, 500);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void getWebViewData() {
        if (title.length() > 0)return;
        if (handler != null) handler.removeMessages(1);
        webView.loadUrl(url1);
        //使webview支持javascript
        WebSettings mSetting = webView.getSettings();
        mSetting.setJavaScriptEnabled(true);

        //添加一个js交互对象
        webView.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");
        //添加一个WebViewClient监听状态，并且在完成时通过js调用java对象的方法
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                view.loadUrl("javascript:window.java_obj.getSource(document.documentElement.outerHTML);void(0)");
//                hideLoading();
                super.onPageFinished(view, url);
            }
        });
    }

    public final class InJavaScriptLocalObj {
        //一定也要加上这个注解,否则没有用
        @JavascriptInterface
        public void getSource(String html) {
            Log.e("=====", "getSource: " + html);
            Document doc = Jsoup.parse(html);
            Elements titleLinks = doc.select("div.cont");

            Log.e("baijiaxin>>>", "doc:" + doc.toString());

            StringBuilder stringBuilder = new StringBuilder();
            for (Element edd : titleLinks) {
                String s = edd.select("p").text();
                stringBuilder.append("    ").append(s).append("\n\n");
            }
            handler.postDelayed(() -> {
                title = stringBuilder.toString();
                Message message = new Message();
                message.obj = title;
                message.what = 1;
                handler.sendMessage(message);
            }, 500);
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    hideLoading();
                    rv.setText(title);
                    break;
            }
        }
    };

}
